﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class MemberController : Base
{
    private readonly ApplicationContext _applicationContext;
    private readonly MemberService _memberService;
    private readonly UserDeptService _adminUserDeptService;
    private readonly UserPostService _adminUserPostService;
    private readonly UserService _adminUserService;
    public MemberController(
        MemberService memberService,
        UserDeptService adminUserDeptService,
        UserPostService adminUserPostService,
        ApplicationContext applicationContext,
        UserService adminUserService
        )
    {
        _memberService = memberService;
        _adminUserDeptService = adminUserDeptService;
        _adminUserPostService = adminUserPostService;
        _applicationContext = applicationContext;
        _adminUserService = adminUserService;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Member_Index)]
    public async Task<IActionResult> ListAsync([FromQuery] QueryMember query)
    {
        ILoginUserInfo user = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        query.Uid = user.UserId;
        query.Uids = await _adminUserService.UserPostAsUids(user);
        PagedInfo<ViewMember> list = await _memberService.GetPageListAsync(query);
        if (query.ExportExcel)
        {
            string sFileName = ExcelHelperAction.ExportExcel(list.Result, "人员列表");
            return Success(new { FilePath = "/export/" + sFileName, fileName = sFileName });
        }
        else
            return Success(new { data = list.Result, count = list.TotalNum });
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Member_Index)]
    public async Task<IActionResult> DeptListTreeAsync()
    {
        var pagedList = await _adminUserDeptService.AsUserDeptTree();
        return Success(new { data = pagedList });
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Member_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        var depts = await _adminUserDeptService.GetUserDeptListAsync();
        var posts = await _adminUserPostService.GetAllAsync();
        if (id < 1)
            return Success(new { depts, posts });
        Member data = await _memberService.GetByIdAsync(id);
        ILoginUserInfo user = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        if (user.GroupId != 1 && data.Uid != user.UserId)
            return Fail("只能修改所属权限的内容");
        return Success(new { data, depts, posts });
    }

    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Member_AddOrEdit)]
    [Log(Name = "新增人员")]
    public async Task<IActionResult> CreatePost([FromBody] EditMember member)
    {
        if (!await _memberService.GetByIdNumberAsync(member.IdNumber))
            return Fail("新增人员已存在，请检查身份证号码");
        ILoginUserInfo adminUser = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        member.Uid = adminUser.UserId;
        Member m = member.Adapt<Member>();
        if (await _memberService.InsertReturnIdAsync(m) > 0)
            return Success($"添加人员：{member.Name} 成功！");
        else
            return Fail("添加失败");
    }

    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Member_AddOrEdit)]
    [Log(Name = "修改人员")]
    public async Task<IActionResult> EditPost([FromBody] EditMember member)
    {
        int res = await _memberService.UpdateAsync(member);
        return res switch
        {
            0 => Fail($"编辑失败：{member.Name} Id:{member.Id}可能是写入数据库错误"),
            -1 => Fail($"请求错误：{member.Name} Id:{member.Id}"),
            -2 => Fail($"该人员已存在:{member.Name}，请重新输入"),
            _ => Success($"修改人员信息:{member.Name} Id:{member.Id}")
        };
    }

    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.Member_Delete)]
    [Log(Name = "删除用户")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _memberService.DeleteAsync(id) > 0)
            return Success("删除用户 id:" + id);
        else
            return Fail("删除失败！");
    }

}
